package logic

import (
	"context"
	"shop/cache"
	"strconv"

	"shop/shopRpc/internal/svc"
	"shop/shopRpc/shopRpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type CartListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewCartListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CartListLogic {
	return &CartListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *CartListLogic) CartList(in *shopRpc.CartListRequest) (*shopRpc.CartListResponse, error) {
	// todo: add your logic here and delete this line
	keys := cache.CartList(in.UserId) //["cart:2:2","cart:2:3"]
	total := 0.0
	var list []*shopRpc.Goods
	for _, key := range keys {
		goodsMap := cache.Rdb.HGetAll(l.ctx, key).Val()
		id, _ := strconv.Atoi(goodsMap["id"])
		price, _ := strconv.ParseFloat(goodsMap["price"], 64)
		quantity, _ := strconv.Atoi(goodsMap["quantity"])
		status, _ := strconv.Atoi(goodsMap["status"])
		goods := &shopRpc.Goods{
			Id:       int64(id),
			Name:     goodsMap["name"],
			Price:    float32(price),
			Quantity: int64(quantity),
			Img:      goodsMap["img"],
			Status:   int64(status),
		}
		total += price * float64(quantity)
		list = append(list, goods)
	}
	return &shopRpc.CartListResponse{
		List:  list,
		Total: float32(total),
	}, nil
}
